import {quillEditor} from 'vue-quill-editor'
import Quill from 'quill'
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'

// 工具栏配置
const toolbarOptions = [
    ['bold', 'italic', 'underline'],
    ['blockquote', 'code-block'],
    [{'header': 1}, {'header': 2}],
    [{'list': 'ordered'}, {'list': 'bullet'}],
    [{'indent': '-1'}, {'indent': '+1'}],
    [{'size': ['small', false, 'large', 'huge']}],
    [{'color': []}, {'background': []}],
    [{'font': []}],
    ['image'],
];

export default {
	components: {
        quillEditor
    },
	data() {
		return {
            id:0,
            ruleForm: {
				name: '',
				postData: {},
                type: 1,
				link:'',
                sort: '',
				url:'',
				radio:"1",
	        },
	        options: [
                {value: 1, label: '链接'},
                {value: 2, label: '图文'}
            ],
            rules: {
                name: [
                    { required: true, message: '请输入图片名称', trigger: 'blur' },
                ]
            },
            imgList:[],				//图片列表
            postData: {},			//七牛云postData
            descImageUrl:'',		//图片
            desc_img:false,			//是否展示删除
            domain:'',				//图片域名

            // 富文本编辑器配置
            header: {token: sessionStorage.token},              //有的图片服务器要求请求头需要有token之类的参数，写在这里
            editorOption: {
                placeholder: '',
                theme: 'snow',                                  //样式
                modules: {
                    toolbar: {
                        container: toolbarOptions,              //工具栏
                        handlers: {
                            'image': function (value) {
                                if (value) {
                                    document.querySelector('.avatar-uploader input').click()
                                } else {
                                    this.quill.format('image', false);
                                }
                            }
                        }
                    }
                }
            },
            uploadData:{},
            upload_url: ''
		}
	},

	//进入页面加载
	mounted: function() {
		var that = this;
		//在缓存中获取值
		that.user_name = sessionStorage.getItem("user_name");
		that.user_id = sessionStorage.getItem("user_id");
		that.token = sessionStorage.getItem("access-token");
		if((!that.token) || (!that.user_id) || (!that.user_name)) {
			that.$router.push('/login');
		}

        // 获取-banner ID
        if(that.$route.query.id) {
            that.id = that.$route.query.id;
            // 获取详情
            that.detail();
        }
        //上传图片地址
        that.upload_url = that.adminApi.upload_url + '/Api/Index/upload_img?dir=Classify';
	},

	//方法
	methods: {
		//请求api
		submitForm(formName) {

			var that = this;
			this.$refs[formName].validate((valid) => {

				if(valid) {
                    if(that.id === 0) {
                        that.add_info();
                    } else {
						that.edit_info();
                    }

				} else {
					console.log('error submit!!');
					return false;
				}
			});
		},

        //获取七牛云token
        getQiNiuToken: function() {
            var that = this;
            //请求登陆接口
            that.$http.post(that.adminApi.api_url + "/api/Qiniu/getToken", {
                token: that.token,
            }, {
                emulateJSON: true
            }).then(
                function(res) {
                    // 处理成功的结果
                    that.postData = {
                        token: res.body.upToken,
                    }
                    that.domain=res.body.domain;
                },
                function() {
                    // 处理失败的结果
                    that.$message({
                        type: 'error',
                        message: `操作提示: ${ '处理异常' }`
                    });
                });
        },

        //上传图片
        //删除
        descRemove(file, fileList) {
            var that = this;
            that.imgList = fileList;
        },
        descPictureCardPreview(file) {
            this.descImageUrl = file.url;
            this.desc_img = true;
            console.log(file);
        },
        descError(res) { //显示错误
            // console.log(res)
        },


        descAvatarSuccess(res, file) { //上传成功后在图片框显示图片
            var that = this;
            console.log(res, file);
            var imageUrl = {
                url: that.adminApi.upload_url + res,
                picture: res,
                uid: file['raw']['uid']
            };
            that.imgList.push(imageUrl);
        },


        //文件超出个数限制时的钩子
        descExceed(files, fileList) {
            this.$message.error('只能上传一张图片');
        },


        /**
         * 轮播详情
         * jihaichuan
         */
        detail:function () {
            var that = this;
            //请求的数据
            var formData = {};
            formData.token = that.token;
            formData.id = that.id;

            //请求邀请者列表
            that.$http.post(that.adminApi.api_url + "/Bannerimg/show_edit", formData, {
                emulateJSON: true
            }).then(
                function(res) {
                    that.ruleForm.name=res.body.title;
                    that.ruleForm.sort=res.body.sort;
                    that.ruleForm.link=res.body.url;
                    that.ruleForm.radio=res.body.status.toString();
                    that.imgList.push({
                        url: that.adminApi.upload_url+res.body.picture,
                        picture: res.body.picture
                    });
                },
                function() {
                    // 处理失败的结果
                    that.$message({
                        type: 'error',
                        message: `操作提示: ${ '处理异常' }`
                    });
                });
        },



        /**
         * 添加-轮播图
         * @returns {boolean}
         */
        add_info:function () {
            var that = this;

            if(that.imgList.length === 0){
                that.$message({
                    type: 'error',
                    message: `操作提示: ${ '请上传图片' }`
                });
                return false;
            }

            //请求的数据
            var formData = {};
            formData.token = that.token;
            formData.title = that.ruleForm.name;
            formData.picture = that.imgList[0]['picture'];
            formData.type = that.ruleForm.type;
            formData.content = that.ruleForm.content;
            formData.url = that.ruleForm.link;
            formData.sort = that.ruleForm.sort;
            formData.status = that.ruleForm.radio;

            //请求邀请者列表
            that.$http.post(that.adminApi.api_url + "/Bannerimg/add", formData, {
                emulateJSON: true
            }).then(
                function(res) {
                    // 处理成功的结果
                    that.$message({
                        type: 'success',
                        message: `操作提示: ${ '添加成功' }`
                    });
                    that.$router.push({path:'/swiper/swiper_list'});
                },
                function() {
                    // 处理失败的结果
                    that.$message({
                        type: 'error',
                        message: `操作提示: ${ '处理异常' }`
                    });
                });
        },

        /**
         * 修改 - 轮播图
         * jihaichuan
         */
        edit_info:function () {
            var that = this;

            //请求的数据
            var formData = that.ruleForm;
            formData.token = that.token;
            formData.id = that.id;
            formData.title = that.ruleForm.name;
            formData.picture = that.imgList[0]['picture'];
            formData.type = that.ruleForm.type;
            if (formData.type == 1) {
                formData.url = that.ruleForm.link;
            } else {
                formData.content = that.ruleForm.content;
            }
            formData.sort = that.ruleForm.sort;
            formData.status = that.ruleForm.radio;

            // console.log(that.imgList);
            // return false;
            //请求API
            that.$http.post(that.adminApi.api_url + "/Bannerimg/edit", formData, {
                emulateJSON: true
            }).then(
                function(res) {
                    // 处理成功的结果
                    that.$message({
                        type: 'success',
                        message: `操作提示: ${ '修改成功' }`
                    });
                    that.$router.push({path:'/swiper/swiper_list'});
                },
                function() {
                    // 处理失败的结果
                    that.$message({
                        type: 'error',
                        message: `操作提示: ${ '处理异常' }`
                    });
                });
        },

        //返回
        cancel:function () {
            var that = this;
            that.$router.push({path:'/swiper/swiper_list'});
        },
	}
}